// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'boyi-5g77xpkp0aa0181c'
})

// 云函数入口函数
exports.main = async (event, context) => {

  // 获取微信上下文
  const wxContext = cloud.getWXContext();

  /** 检查是否正确获取用户的openId start */
  if(wxContext.OPENID == undefined) {
    var result = {};
    result.errCode = 1;
    result.errMsg = "未能正确返回openId";
    var data = {};
    result.data = data;
    return result;
  }
  /** 检查是否正确获取用户openId end */

  /** 检查传参是否完整 start */
  if(event.name == undefined || event.date == undefined || event.timeSlot == undefined || event.region == undefined || event.temperature == undefined || event.otherInfo == undefined) {
    var result = {};
    result.errCode = 2;
    result.errMsg = "传入参数不完整";
    var data = {};
    result.data = data;
    return result;
  }
  /** 检查传参是否完整 end */

  // 实例化数据库
  const db = cloud.database();

  /** 检查是否重复填报同天同一时间段 start */
  var healthInfo;
  console.log(wxContext.OPENID);
  console.log(event.date);
  console.log(event.timeSlot);
  await db.collection('healthReport')
  .where({
    openId: wxContext.OPENID,
    date: event.date,
    timeSlot: event.timeSlot
  })
  .get()
  .then(res => {
    console.log(res.data);
    healthInfo = res.data[0];
  })
  /** 检查是否重复填报同天同一时间段 end */

  // 如果存在重复填报通天同一时间段
  if(healthInfo != undefined) {
    var result = {};
    result.errCode = 0;
    result.errMsg = "该天该时间段已经填报过";
    var data = {};
    data.ok = false;
    result.data = data;
    return result;
  }

  // 填写并返回参数
  var _otherInfo = event.otherInfo;
  await db.collection('healthReport')
  .add({
    data: {
      openId: wxContext.OPENID,
      name: event.name,
      date: event.date,
      region: event.region,
      timeSlot: event.timeSlot,
      temperature: event.temperature,
      otherInfo: _otherInfo
    }
  })
  .then(res => {
    console.log(res);
  })
  var result = {};
  result.errCode = 0;
  result.errMsg = "上报成功";
  var data = {};
  data.ok = true;
  result.data = data;
  return result;
}